package com.eascs.dubbo.api.admin;

import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.api.loanapply.CreditPermitService;
import com.eascs.admin.item.service.O2oPubDdItemService;
import com.eascs.admin.o2o.detail.controller.LoanDetailRestController;
import com.eascs.admin.o2o.finance.entity.O2oFinanceFlowEntity;
import com.eascs.admin.o2o.finance.service.O2oFinanceFlowService;
import com.eascs.admin.o2o.internal.service.WfTypeStatusService;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2OWorkFlowService;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oLoadUserZxServiceImpl;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.admin.o2o.specialInterview.service.O2OSpecialInterviewService;
import com.eascs.admin.o2o.zx.entity.O2oLoanUserEntityZx;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.crm.nsEditDetail.service.ContactsInfoService;
import com.eascs.crm.nsEditDetail.service.CustomerAssetInfoService;
import com.eascs.crm.nsEditDetail.service.CustomerShopInfoService;
import com.eascs.dubbo.api.util.UserUtils;
import com.eascs.gaczcontract.entity.CustomerBasicInfo;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.EmployeeService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;

/**
 * 征信准入实现类-dubbo接口实现类
 * 
 * @author GYH
 *
 */
@Service
public class CreditPermitServiceImpl implements CreditPermitService {

	private static final Logger logger = LoggerFactory.getLogger(CreditPermitServiceImpl.class);

	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Reference
	private WorkFlowService workFlowService;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	@Autowired
	private O2oFinanceFlowService financeFlowService;
	@Autowired
	O2oLoanService o2oLoanService;
	@Value("${o2o.admin.depositeUrl}")
	private String depositeUrl;
	@Autowired
	LoanDetailRestController loanDetailRestController;
	@Autowired
	O2oZxServiceImpl o2oZxServiceImpl;
	@Autowired
	O2oLoadUserZxServiceImpl o2oLoadUserZxServiceImpl;
	@Autowired
	O2OSpecialInterviewService o2OSpecialInterviewService;
	@Autowired
	O2OWorkFlowService o2oWorkFlowService;
	@Autowired
	O2oPubDdItemService o2oPubDdItemService;
	@Autowired
	ContactsInfoService contactsInfoService;
	@Autowired
	CustomerShopInfoService customerShopInfoService;
	@Autowired
	CustomerAssetInfoService customerAssetInfoService;
	@Reference
	CustomerService customerService;
	@Reference
	EmployeeService employeeService;
	@Autowired
	WfTypeStatusService wfTypeStatusService;
	@Value("${o2o.admin.wf.zxUrl}")
	private String zxUrl;
	@Value("${o2o.admin.wf.nsUrl}")
	private String nsUrl;
	@Value("${o2o.admin.wf.sbzjUrl}")
	private String sbzjUrl;
	@Value("${o2o.admin.wf.cwshUrl}")
	private String cwshUrl;// 财务审核详情页url
	@Value("${o2o.admin.wf.NewZxUrl}")
	private String NewZxUrl;

	/**
	 * 启动征信准入流程
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@Override
	public String startCreditPermit(String loanapplyNo) {
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(loanapplyNo);
		logger.info("贷款对象：{[]}", o2oLoanapplyEntity);
		O2oLoanUserEntity SpouseEntity = o2oLoanUserService.findSpouseId(o2oLoanapplyEntity.getLoanId(),
				o2oLoanapplyEntity.getLoanapplyNo());
		if (SpouseEntity != null) {
			if (StringUtil.isEmpty(SpouseEntity.getZxNo())) {
				return "请选择配偶的征信报告";
			}
			O2oZxEntity mateZx = o2oZxServiceImpl.getEntityById(SpouseEntity.getZxNo());
			if (!"CLO".equals(mateZx.getZxStatus())) {
				return "选择的配偶的征信报告流程未结束";
			}
			
			O2oLoanUserEntityZx o2oLoanUserMateEntityZx = o2oLoadUserZxServiceImpl.getEntityByZxNo(SpouseEntity.getZxNo());

			if (o2oLoanUserMateEntityZx.getZxDate() != null) {
				boolean flag = isValid(o2oLoanUserMateEntityZx.getZxDate(), 30);
				if (!flag) {
					return "选择的配偶的征信报告已经超过30天有效期";
				}
			}
			
			// 检查配偶信息
			// check是否编辑配偶关系
			// 1.查询配偶有没存在 2.不存在 ：检测是否有新增配偶关系
			String checkSpouse = checkSpouseZX(SpouseEntity.getLoanId());
			if (!checkSpouse.equals(StatusContexts.SUCCESS)) {
				return checkSpouse;
			}
		}
		O2oLoanUserEntity basicEntity = o2oLoanUserService.findById(o2oLoanapplyEntity.getLoanId(),
				o2oLoanapplyEntity.getLoanapplyNo());
		// 检查借款人信息
		String checkLoaner = checkZX(basicEntity, o2oLoanapplyEntity);
		if (!checkLoaner.equals(StatusContexts.SUCCESS)) {
			return checkLoaner;
		}
		if (StringUtil.isEmpty(basicEntity.getZxNo())) {
			return "请选择借款人的征信报告";
		}
		O2oZxEntity userZx = o2oZxServiceImpl.getEntityById(basicEntity.getZxNo());
		if (!"CLO".equals(userZx.getZxStatus())) {
			return "选择的借款人的征信报告流程未结束";
		}

		O2oLoanUserEntityZx o2oLoanUserEntityZx = o2oLoadUserZxServiceImpl.getEntityByZxNo(basicEntity.getZxNo());

		if (o2oLoanUserEntityZx.getZxDate() != null) {
			boolean flag = isValid(o2oLoanUserEntityZx.getZxDate(), 30);
			if (!flag) {
				return "选择的借款人的征信报告已经超过30天有效期";
			}
		}
		// check贷款信息
		String checkLoanApply = checkLoanApply(o2oLoanapplyEntity);
		if (!checkLoanApply.equals(StatusContexts.SUCCESS)) {
			return checkLoanApply;
		}
		WFRequestParam param = new WFRequestParam();
		param.setReferId(o2oLoanapplyEntity.getLoanapplyNo());
		param.setReferCode(o2oLoanapplyEntity.getBillCode());
		param.setReferUrl(zxUrl);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType("PROCESS_ACCESS");
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(o2oLoanapplyEntity.getLtd());
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(o2oLoanapplyService
				.findLoanUserEntity(o2oLoanapplyEntity.getLoanapplyNo(), o2oLoanapplyEntity.getLoanId())
				.getUserFullName());
		appliedDes.append("，申请金额:");
		java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); // 格式化，保留两位小数
		appliedDes.append(df.format(o2oLoanapplyEntity.getLoanaMount().doubleValue()));
		param.setAppliedDes(appliedDes.toString());
		param.setLoginUser(UserUtils.getUser(user));
		logger.info("提交征信准入，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】",
				o2oLoanapplyEntity.getLoanapplyNo(), o2oLoanapplyEntity.getBillCode(),
				ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), o2oLoanapplyEntity.getLtd(),
				appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()!=null) {
			o2oLoanapplyService.updateWorkFlowStatus(StatusContexts.O2O_ZX_BEGIN, o2oLoanapplyEntity.getLoanapplyNo());
			wfTypeStatusService.updatefindRUN(o2oLoanapplyEntity.getLoanapplyNo(), StatusContexts.WFTYPE_ZX);
			// 启动财务审核流程
			if (o2oLoanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)
					&& StatusContexts.OPERATION_MODEL_PTDB.equals(o2oLoanapplyEntity.getOperationModel())) {
				O2oFinanceFlowEntity entity = financeFlowService.getByLoanApplyno(loanapplyNo);
				if (entity != null && entity.getFlowStatus().equals(StatusContexts.O2O_BANK_NEW)) {
					startUpFinance(loanapplyNo);
				}
				if (entity == null) {
					startUpFinance(loanapplyNo);
				}
			}
			return "1";
		} else {
			logger.error("提交征信准入失败，错误信息{},{}",modelResult.getErrMsg(),modelResult.getDetailStack());
		}
		return modelResult.getErrMsg();
	}
    
	private boolean isValid(Date dt1, int day) {
		boolean flag = true;
		Calendar now = Calendar.getInstance();
		now.setTime(new Date());
		now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
		Date dt2 = now.getTime();

		if (dt1.getTime() < dt2.getTime()) {
			System.out.println("dt1在dt2后");
			flag = false;
		}
		return flag;
	}
	
	public String checkSpouseZX(String id) {
		CustomerEntity basicEntity = customerService.queryCustomerEntityByCustomerId(id);
		boolean familyName = StringUtil.isEmpty(basicEntity.getCustomerFamilyName()); // 配偶姓
		boolean givenName = StringUtil.isEmpty(basicEntity.getCustomerGivenName()); // 配偶名
		boolean idType = StringUtil.isEmpty(basicEntity.getIdType()); // 配偶证件类型
		boolean idNumber = StringUtil.isEmpty(basicEntity.getIdNumber()); // 配偶证件号码
		boolean mobileNumber = StringUtil.isEmpty(basicEntity.getMobileNumber()); // 联系电话
		boolean licenseExpirationDate = StringUtil.isEmpty(basicEntity.getLicenseExpirationDate()); // 证件到期日
		boolean MaritalStatus = StringUtil.isEmpty(basicEntity.getMaritalStatus()); // 婚姻状况
		if (familyName) {
			return "配偶姓不能为空，请编辑借款人信息";
		}
		if (givenName) {
			return "配偶名不能为空，请编辑借款人信息";
		}
		if (idType) {
			return "配偶证件类型不能为空，请编辑借款人信息";
		}
		if (idNumber) {
			return "配偶证件号码不能为空，请编辑借款人信息";
		}
		if (mobileNumber) {
			return "配偶联系电话不能为空，请编辑借款人信息";
		}
		if (licenseExpirationDate) {
			return "配偶证件到期日不能为空，请编辑借款人信息";
		}
		if (MaritalStatus) {
			return "配偶婚姻状况不能为空，请编辑借款人信息";
		}
		return StatusContexts.SUCCESS;

	}

	public String checkZX(O2oLoanUserEntity basicEntity, O2oLoanapplyEntity o2oLoanapplyEntity) {
		if (basicEntity == null) {
			logger.info("获取客户信息失败！或是客户不存在");
			return "获取客户信息失败！或是客户不存在";
		} else {
			logger.info("获取客户信息结果：customer：{[]}", basicEntity.toString());
		}
		CustomerBasicInfo customerBasicInfo = o2oLoanapplyService.getCustomerEntityById(basicEntity.getId());// 查询借款人扩展信息
		boolean familyName = StringUtil.isEmpty(basicEntity.getUserSurName()); // 借款人姓
		boolean givenName = StringUtil.isEmpty(basicEntity.getUserName()); // 借款人名
		boolean idType = StringUtil.isEmpty(basicEntity.getDocumentType()); // 证件类型
		boolean idNumber = StringUtil.isEmpty(basicEntity.getDocumentNo()); // 证件号码
		boolean licenseExpirationDate = StringUtil.isEmpty(customerBasicInfo.getLicenseExpirationDate()); // 证件到期日
		boolean customerName = StringUtils.isBlank(o2oLoanapplyEntity.getCustomeRname()); // 客户名称
		boolean mobileNumber = StringUtil.isEmpty(basicEntity.getUserPhone()); // 联系电话
		boolean customerSd = StringUtils.isBlank(o2oLoanapplyEntity.getCustomerNo());// 客户sd号
		if (familyName) {
			return "借款人姓不能为空，请编辑借款人信息";
		}
		if (givenName) {
			return "借款人名不能为空，请编辑借款人信息";
		}
		if (idType) {
			return "借款人证件类型不能为空，请编辑借款人信息";
		}
		if (idNumber) {
			return "借款人证件号码不能为空，请编辑借款人信息";
		}
		if (licenseExpirationDate) {
			return "证件到期日不能为空，请编辑借款人信息";
		}
		if (mobileNumber) {
			return "借款人联系电话不能为空，请编辑借款人信息";
		}
		if (!(StatusContexts.LOAN_TYPE_BP.equals(o2oLoanapplyEntity.getLoanType())
				||StatusContexts.LOAN_TYPE_BP_JX.equals(o2oLoanapplyEntity.getLoanType())
				||StatusContexts.LOAN_TYPE_SG.equals(o2oLoanapplyEntity.getLoanType())
				||StatusContexts.LOAN_TYPE_YC.equals(o2oLoanapplyEntity.getLoanType())
				||StatusContexts.LOAN_TYPE_SC.equals(o2oLoanapplyEntity.getLoanType()))) {
			if (customerName) {
				return "借款人客户名称不能为空，请编辑借款人信息";
			}
			if (customerSd) {
				return "借款人客户号不能为空，请编辑借款人信息";
			}
		}
		return StatusContexts.SUCCESS;
	}

	private String checkLoanApply(O2oLoanapplyEntity loan) {
		String result = "SUCCESS";
		if (StringUtil.isBlank(loan.getLoanType())) {
			return "贷款类型不能为空，请编辑贷款信息";
		}
		if (StringUtil.isBlank(loan.getLtd())) {
			return "经办平台不能为空，请编辑贷款信息";
		}
		if (StringUtil.isBlank(loan.getOperatorNo())) {
			return "信贷经理不能为空，请编辑贷款信息";
		}
		if (StringUtil.isBlank(loan.getOperationModel())) {
			return "经营模式不能为空，请编辑贷款信息";
		}
		if (StatusContexts.LOAN_TYPE_BK.equals(loan.getLoanType()) && StringUtil.isBlank(loan.getCustomerNo())) {
			return "SD客户名称不能为空，请编辑贷款信息";
		}
		if ((StatusContexts.LOAN_TYPE_BP.equals(loan.getLoanType())
				|| StatusContexts.LOAN_TYPE_BP_JX.equals(loan.getLoanType())
				|| StatusContexts.LOAN_TYPE_SG.equals(loan.getLoanType())
				|| StatusContexts.LOAN_TYPE_YC.equals(loan.getLoanType())
				|| StatusContexts.LOAN_TYPE_SC.equals(loan.getLoanType())) && StringUtil.isBlank(loan.getPartnerId())) {
			return "渠道名称不能为空，请编辑贷款信息";
		}
		if (null == loan.getLoanaMount()) { 
			return "申请金额不能为空，请编辑贷款信息";
		}
		return result;
	}

	/**
	 * 提交财务审核
	 * 
	 * @return
	 */
	public void startUpFinance(String loanapplyNO) {
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(loanapplyNO);
		O2oFinanceFlowEntity entity = financeFlowService.getByLoanApplyno(loanapplyNO);
		if (entity == null) {
			entity = new O2oFinanceFlowEntity();
			entity.setBillCode(loan.getBillCode());
			entity.setLoanapplyno(loan.getLoanapplyNo());
			entity.setFlowStatus(StatusContexts.O2O_BANK_NEW);
			entity.setRemark("提交财务审核，贷款id:" + loan.getLoanapplyNo());
			User user = UserHolder.getUser();
			entity.setStartupOperno(user.getNo());
			entity.setStartupOpername(user.getCname());
			financeFlowService.insert(entity);
		}
		WFRequestParam param = new WFRequestParam();
		param.setReferId(loan.getLoanapplyNo());
		param.setReferCode(loan.getBillCode());
		param.setReferUrl(cwshUrl);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_FINANCE_AUDIT));
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(loan.getLtd());
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(
				o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(), loan.getLoanId()).getUserFullName());
		appliedDes.append("，申请金额:");
		java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); // 格式化，保留两位小数
		appliedDes.append(df.format(loan.getLoanaMount().doubleValue()));
		param.setAppliedDes(appliedDes.toString());
		param.setLoginUser(UserUtils.getUser(user));
		logger.info("提交财务审核，参数有贷款id：【{[]}】，贷款编号：【{[]}】，系统模块：【{[]}】，流程类型：【{[]}】，经营平台id：【{[]}】，贷款摘要信息：【{[]}】",
				loan.getLoanapplyNo(), loan.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(),
				loan.getLtd(), appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			entity.setStartupTime(new Date());
			entity.setFlowStatus(StatusContexts.O2O_BANK_RUN);
			financeFlowService.update(entity);
			logger.info("info:{[]}", "提交成功");
			// return BaseRestResult.info("提交成功").andRefresh();
		} else {
			logger.error("提交征信失败，错误信息{[]}", modelResult.getDetailStack());
			// return BaseRestResult.warn(modelResult.getErrMsg());
		}
	}
	
}
